<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="8" :sm="24">
            <a-form-item style="display: flex">
              <div style="display: flex">
                <a-select v-model="queryParam.searchType" placeholder="请选择" style="width: 130px">
                  <a-select-option v-for="(item, index) in condition.searchTypeList" :key="index" :value="item.key">{{ item.value }}</a-select-option>
                </a-select>
                <a-input v-model="queryParam.searchValue" placeholder="请输入" style="margin-left: 5px" />
              </div>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-select v-model="queryParam.brandList" placeholder="品牌（多选）" :getPopupContainer="triggerNode => triggerNode.parentNode" show-search mode="multiple">
                <a-select-option v-for="(item, index) in condition.brandList" :key="index" :value="item.key">{{ item.value }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-range-picker style="width: 100%" :show-time="{ format: 'YYYY-MM-DD HH:mm:ss' }" v-model="regTime" :placeholder="['开始时间', '结束时间']" @change="onChangeType" />
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-select v-model="queryParam.classifyList" placeholder="分类（多选）" autoClearSearchValue show-search allowClear mode="tags">
                <a-select-option v-for="(item, index) in condition.classifyList" :key="index" :value="item.key">{{ item.value }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-form-item>
                <a-select v-model="queryParam.publisherCode" placeholder="发布方" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option v-for="(item, index) in condition.publisherList" :key="index" :value="item.key">{{ item.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-form-item>
                <a-select v-model="queryParam.isShelf" placeholder="状态" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option v-for="(item, index) in condition.shelfList" :key="index" :value="item.key">{{ item.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="24" :sm="24">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
              <a-button type="primary" @click="searchQuery">查询</a-button>
              <a-button @click="searchReset" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col> -->
        </a-row>
        <a-row :gutter="24">
          <!-- 新增 -->
          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-select v-model="queryParam.verifiedStatusList" placeholder="审核状态" :getPopupContainer="triggerNode => triggerNode.parentNode" show-search mode="multiple">
                <a-select-option v-for="(item, index) in condition.verifiedStatusList" :key="index" :value="item.key">{{ item.value }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="16" :sm="24">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
              <a-button type="primary" @click="searchQuery">查询</a-button>
              <a-button @click="searchReset" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="addHandle"> 新增 </a-button>
              <a-popconfirm ok-text="Yes" title="确定上架吗？" cancel-text="No" @confirm="handleUpOrDown(1)">
                <a-button style="margin-left: 8px" :disabled="selectedRowKeys.length < 1">上架</a-button>
              </a-popconfirm>
              <a-popconfirm ok-text="Yes" title="确定下架吗？" cancel-text="No" @confirm="handleUpOrDown(0)">
                <a-button style="margin-left: 8px" :disabled="selectedRowKeys.length < 1">下架</a-button>
              </a-popconfirm>
              <a-button style="margin-left: 8px" :disabled="selectedRowKeys.length < 1" @click="addShareClick"> 加入分享列表 </a-button>
            </span>
            <span style="float: right">
              <a-button @click="shareClick"> 分享列表 </a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :rowSelection="rowSelection" :pagination="pagination" :scroll="{ x: 1300 }">
      <span slot="record" slot-scope="text, record, index" style="display: inline-block; word-wrap: wrap">
        <a style="width: 100%; font-weight: 600" @click="showRecord(record)" :class="record.posThemeExt.verifiedStatus == 100 ? 'noConfirm' : ''">
          <template v-if="record.posThemeExt.verifiedStatus == 0">未投稿</template>
          <template v-else-if="record.posThemeExt.verifiedStatus == 1">待审核</template>
          <template v-else-if="record.posThemeExt.verifiedStatus == 2">审核中</template>
          <template v-else-if="record.posThemeExt.verifiedStatus == 3">审核通过</template>
          <template v-else-if="record.posThemeExt.verifiedStatus == 4">审核驳回</template>
          <template v-else-if="record.posThemeExt.verifiedStatus == 100">素材待确认</template>
        </a>
        <br />
        <a class="img-item" @click="commodity(record)">
          {{ record.name }}
        </a>
      </span>
      <span slot="avatarslot" slot-scope="text, record, index">
        <img :src="record.videoDetail.coverUrl.split(',')[0]" style="width: 50px; height: 50px" @click="commodity(record)" v-if="record.videoDetail.coverUrl" />
        <img :src="record.backgroundImage" style="width: 50px; height: 50px" @click="commodity(record)" v-else />
        <!-- <img :src="record.backgroundImage" style="width: 50px; height: 50px" /> -->
      </span>
      <span slot="status" slot-scope="text, record">
        <span v-if="record.isShelf == 0">下架</span>
        <span v-if="record.isShelf == 1">上架</span>
        <span v-if="record.isShelf == 2">待上架</span>
      </span>
      <span slot="brand" slot-scope="text, record, index">
        <div v-if="record.brand">
          <a-tag style="margin: 2px" color="blue" v-for="(label, index) in record.brand.split(',')" :key="index">
            {{ label }}
          </a-tag>
        </div>

        <span v-else></span>
      </span>
      <span slot="action" slot-scope="text, record">
        <router-link :to="`/pos+/match/collocation/edit/${record.id + 'detail'}`">查看详情</router-link>
        <a-divider type="vertical" />
        <!-- <router-link :to="`/pos+/match/collocation/edit/${record.id}`">编辑</router-link> -->
        <!-- 审核通过 -->
        <a-popconfirm
          v-if="record.posThemeExt.verifiedStatus == 3"
          ok-text="Yes"
          title="编辑该素材后需要重新审核，是否确认编辑"
          cancel-text="No"
          @confirm="$router.push(`/pos+/match/collocation/edit/${record.id}`)"
        >
          <a>编辑</a>
        </a-popconfirm>
        <a v-else class="img-item" @click="$router.push(`/pos+/match/collocation/edit/${record.id}`)"> 编辑 </a>
        <a-divider type="vertical" />
        <a-popconfirm ok-text="Yes" title="确定上架吗？" cancel-text="No" @confirm="handleUp(1, record.id)" v-if="record.isShelf === 0">
          <a>上架</a>
        </a-popconfirm>
        <a-popconfirm title="确定下架吗？" ok-text="Yes" cancel-text="No" @confirm="handleUp(0, record.id)" v-if="record.isShelf === 1">
          <a>下架</a>
        </a-popconfirm>
        <a-popconfirm title="确定上架吗？" ok-text="Yes" cancel-text="No" @confirm="handleUp(1, record.id)" v-if="record.isShelf === 2">
          <a>上架</a>
        </a-popconfirm>

        <a-divider type="vertical" />
        <a-popconfirm title="确定删除吗？" @confirm="handleMatchDelete(record.id)">
          <a-icon slot="icon" type="question-circle-o" style="color: red" />
          <a href="javascript:;">删除</a>
        </a-popconfirm>
        <a-divider type="vertical" />
        <a @click="handleLog(record.id)">日志</a>
      </span>
    </s-table>

    <aRecord v-if="isaRecord" ref="aRecord" :themeId="themeId" @closeRecord="closeRecord" @updateTable="updateTable"></aRecord>
    <BigImg :visibleImgs="visibleImgs" :imgList="imgList" :goToIndex="goToIndex" @closeBig="closeBig"></BigImg>
    <Log :logVisible.sync="logVisible" ref="log"></Log>
    <CommodityModel ref="commodityModel"></CommodityModel>
    <Share ref="share"></Share>
  </a-card>
</template>

<script>
import aRecord from './components/record'
import { goodsSkcDetail } from '@/api/pos/index.js'
import BigImg from '@/views/box/components/UserMsg/bigImg'
import CommodityModel from '../guide/components/commodityModel.vue'
import Share from './share'
import { STable } from '@/views/box/components'
import Log from '@/views/box/boxLook/components/Log'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import { conditionList, themeList, themeStatus, themeDetail, addPack } from '@/api/pos/match'
const columns = [
  {
    title: 'ID',
    align: 'center',
    dataIndex: 'lookId',
    width: 80
  },
  {
    title: '名称',
    align: 'center',
    dataIndex: 'record',
    scopedSlots: { customRender: 'record' },
    width: 160
  },
  // {
  //   title: '审核状态',
  //   align: 'center',
  //   dataIndex: 'verifiedStatus',
  //   scopedSlots: { customRender: 'verifiedStatus' },
  //   width: 160
  // },
  {
    title: '效果图',
    align: 'center',
    dataIndex: 'containsProduct',
    scopedSlots: { customRender: 'avatarslot' },
    width: 80
  },
  {
    title: '适用品牌',
    align: 'center',
    dataIndex: 'brand',
    scopedSlots: { customRender: 'brand' },
    width: 240
  },

  {
    title: '分类',
    align: 'center',
    dataIndex: 'classifyName',
    width: 120
  },
  {
    title: '发布方',
    align: 'center',
    dataIndex: 'publisherName',
    width: 140
  },
  {
    title: '发布时间',
    align: 'center',
    width: 200,
    dataIndex: 'putAwayTime'
  },
  {
    title: '状态',
    align: 'center',
    scopedSlots: { customRender: 'status' },
    width: 80
  },
  {
    title: '创建时间',
    align: 'center',
    width: 200,
    dataIndex: 'createTime'
  },

  {
    title: '创建人',
    align: 'center',
    dataIndex: 'creatorName',
    width: 80
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    width: 240,
    fixed: 'right'
  }
]
export default {
  components: {
    STable,
    Log,
    BigImg,
    CommodityModel,
    aRecord,
    Share
  },
  data() {
    return {
      showImg: '',
      regTime: [],
      showVisible: false,
      logVisible: false,
      productDetails: {},
      visible: false,
      visibleImgs: false,
      columns,
      searchTypeList: [],
      imgList: [],
      goToIndex: 0,
      queryParam: {
        channelType: 'retailTheme',
        loginWorkNo: this.$store.getters.userInfo.workNo
      },
      condition: {},
      pagination: {
        pageSize: 10,
        page: 1,
        current: 1,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      userInfo: Vue.ls.get(USER_INFO),
      loadData: parameter => this.fetchData(parameter),
      selectedRows: [],
      selectedRowKeys: [],
      themeId: '',
      isaRecord: false
    }
  },
  mounted() {
    this.postCondition()
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        onSelect: this.onSelect,
        onSelectAll: this.onSelectAll
      }
    }
  },
  watch: {
    $route(to, from) {
      if (from.path.includes('/pos+/match/collocation/edit') && to.path.includes('/pos+/match/collocation/index')) {
        this.$refs.table.refresh()
      } else {
        let currentPath = this.$route.path
        if (currentPath.includes('/pos+/match/collocation/index')) {
          this.$refs.screen.reset()
          this.selectedRowKeys = []
        }
      }
    }
  },
  methods: {
    onSelect(record, selected) {
      if (selected == true) {
        this.selectedRows.push(record)
      } else {
        this.selectedRows.forEach(function (item, index, arr) {
          if (item.id == record.id) {
            arr.splice(index, 1)
          }
        })
      }
      console.log(this.selectedRows, 'this.selectionRows111')
      //--update-end----author:kangxiaolin---date:20190921------for:系统发送通知 用户多选失败 #513----
    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected === true) {
        for (var a = 0; a < changeRows.length; a++) {
          this.selectedRows.push(changeRows[a])
        }
      } else {
        for (var b = 0; b < changeRows.length; b++) {
          this.selectedRows.splice(this.selectedRows.indexOf(changeRows[b]), 1)
        }
      }
      console.log(this.selectedRows, 'this.selectionRows222')
    },
    // 回复刷新
    updateTable() {
      this.postCondition()
    },
    closeRecord() {
      this.isaRecord = false
    },
    //加入分享列表
    addShareClick() {
      let lookIds = this.selectedRows.map(item => item.lookId)
      let params = {
        lookIds: lookIds,
        workNo: this.userInfo.workNo
      }
      addPack(params).then(res => {
        if (res.code == 200) {
          this.$message.success('加入成功!')
          this.$refs.table.refresh(true)
          this.selectedRowKeys = []
          this.selectedRows = []
        }
      })
    },
    // 分享列表
    shareClick() {
      this.$refs.share.show()
    },
    // 新增
    async addHandle() {
      let data = {
        workNo: this.$store.getters.userInfo.workNo
      }
      const res = await themeDetail(data)
      if (res.code == 200) {
        this.$router.push(`/pos+/match/collocation/edit/${'add'}`)
      } else {
        this.$message.error(res.msg || res.message)
      }
    },
    showRecord(record) {
      // this.$refs.aRecord.visible = true
      this.isaRecord = true
      this.themeId = record.id
    },
    fetchData(parameter) {
      const queryParam = JSON.parse(JSON.stringify(this.queryParam))
      const data = {}
      data.themeListQto = queryParam

      data.themeListQto.current = parameter.pageNo
      data.themeListQto.size = parameter.pageSize
      // delete queryParam.regTime
      return themeList(data.themeListQto).then(res => {
        if (res.code === 200) {
          res.data.records.forEach(element => {
            if (element.backgroundImage) {
              let url = element.backgroundImage.indexOf('?')
              if (url == '-1') {
                element.backgroundImage = element.backgroundImage + '?imageView2/0/format/jpg/q/75'
              }
            }
          })

          this.pagination.current = res.data.current
          const { total, size, current } = res.data
          const data = {
            page: {
              count: total,
              pageNo: current,
              pageSize: size,
              pages: Math.ceil(total / size)
            },
            data: res.data.records
          }
          console.log(data, 'data')
          return data
        } else {
          this.$message.error(res.msg || res.message)
          const data = {
            page: {
              pageNo: 0,
              count: 0,
              pageSize: 10
            },
            data: []
          }
          return data
        }
      })
    },
    onChangeType(value, dateString) {
      this.queryParam.startDate = dateString[0]
      this.queryParam.endDate = dateString[1]
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
      console.log(selectedRowKeys, '  this.selectedRowKeys')

      // this.selectedRows = selectedRows
    },
    postCondition() {
      let params = {
        channelType: 'retailTheme'
      }
      conditionList(params).then(res => {
        if (res.code == 200) {
          this.condition = res.data
        }
      })
    },
    // 查看大图
    bigImg(index, list, type) {
      console.log(index, list, type)
      if (type === 'styleList') {
        this.imgList = list.map(item => {
          if (item.img) {
            item.value = item.img
          }
          return item.value
        })
      } else if (type === 'photo') {
        this.imgList = [list]
      }
      this.goToIndex = index
      setTimeout(() => {
        this.visibleImgs = true
      }, 100)
    },
    // 关闭大图
    closeBig(value) {
      this.visibleImgs = value
      setTimeout(() => {
        this.imgList = []
      }, 200)
    },
    searchQuery() {
      this.$refs.table.refresh(true)
    },
    searchReset() {
      this.queryParam = {
        channelType: 'retailTheme',
        loginWorkNo: this.$store.getters.userInfo.workNo
      }
      this.regTime = null
      this.$refs.table.refresh(true)
    },
    handleUpOrDown(type) {
      const data = {
        ids: this.selectedRowKeys,
        isShelf: type, // :1上架，0下架
        isDelete: false,
        realname: this.userInfo.realname,
        workNo: this.userInfo.workNo
      }
      themeStatus(data).then(res => {
        if (res.code == 200) {
          this.selectedRowKeys = []
          setTimeout(() => {
            this.$refs.table.refresh()
          }, 1000)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleUp(type, id) {
      const data = {
        id: id,
        isShelf: type, // :1上架，0下架
        isDelete: false,
        realname: this.userInfo.realname,
        workNo: this.userInfo.workNo
      }
      themeStatus(data).then(res => {
        if (res.code == 200) {
          this.selectedRowKeys = []
          setTimeout(() => {
            this.$refs.table.refresh()
          }, 1000)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleMatchDelete(id) {
      const data = {
        id: id,
        isDelete: true,
        realname: this.userInfo.realname,
        workNo: this.userInfo.workNo
      }
      themeStatus(data).then(res => {
        if (res.code == 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleShowImg(url) {
      this.showImg = url
      this.showVisible = true
    },
    handleLog(id) {
      this.$refs.log.getLog(id, 'parent')
      this.logVisible = true
    },
    // handleDetails(id) {},
    // 商品
    commodity(record) {
      this.$refs.commodityModel.show(record)
    }
  }
}
</script>
<style lang="less" scoped>
.show-img {
  display: block;
  width: 100%;
}

.details-wrapper {
  display: flex;
  padding-bottom: 40px;

  .main-img {
    display: block;
    width: 40%;
  }

  .text {
    flex: 1;
    margin-left: 10%;
    line-height: 35px;
    font-size: 14px;
  }
}

.id-wrapper {
  font-size: 12px;
  text-align: center;

  span {
    color: #999;
  }
}

.product-img {
  font-size: 12px;

  .img-item {
    display: inline-block;
    vertical-align: middle;
    margin: 0 5px;
    text-align: center;
  }
}

.time {
  font-size: 12px;
  color: #999;
}

.img {
  display: block;
  margin: 2px auto;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}
.noConfirm {
  color: rgba(245, 154, 35, 0.847058823529412);
}
</style>
